package com.bosssoft.permission.centre.service.impl;

/**
 * @Author: wang
 * @Time: 2022/3/18
 */

import com.alibaba.fastjson.JSON;
import com.bosssoft.permission.centre.dao.mapper.*;
import com.bosssoft.permission.centre.entity.*;
import com.bosssoft.permission.centre.pojo.dto.pcp.PcpUserDTO;
import com.bosssoft.permission.centre.pojo.dto.pcp.RoleDTO;
import com.bosssoft.permission.centre.pojo.dto.pcp.UserDTO;
import com.bosssoft.permission.centre.pojo.query.UserQuery;
import com.bosssoft.permission.centre.service.UserService;
import com.bosssoft.permission.centre.service.exception.UserCentreExceptionCode;

import com.bosssoft.permission.centre.service.util.Md5Utils;
import com.bosssoft.permission.centre.service.util.SendMQMessageUtil;
import com.github.pagehelper.Page;
import com.sd365.common.core.annotation.stuffer.IdGenerator;
import com.sd365.common.core.common.aop.MyPageInfo;
import com.sd365.common.core.common.exception.BusinessException;
import com.sd365.common.core.common.exception.code.BusinessErrorCode;
import com.sd365.common.core.context.BaseContextHolder;
import com.sd365.common.core.mq.ActionType;
import com.sd365.common.util.BeanException;
import com.sd365.common.util.BeanUtil;
import com.sd365.common.util.StringUtil;


import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import tk.mybatis.mapper.entity.Example;


import javax.validation.Valid;
import java.sql.Date;
import java.sql.Time;
import java.util.Calendar;
import java.util.List;

@Slf4j
@Service
public class UserServiceImpl extends AbstractBaseDataServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private IdGenerator idGenerator;

    @Autowired
    private UserRoleMapper userRoleMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private DepartmentMapper departmentMapper;
    @Autowired
    private PositionMapper positionMapper;

    @Autowired
    private SendMQMessageUtil sendMQMessageUtil;
    private static final Long DRIVER_ID = 1346692911269543943L;
    private static final String TABLE_NAME = "driver";


    @Override
    public Boolean add(@Valid UserDTO userDTO) {
        log.info("这里是1号位");
        if (userMapper.selectByCode(userDTO.getCode()) != null || StringUtil.isEmpty(userDTO.getPassword())) {
            return false;
        }
        log.info("打印增加的userDTO2信息");
        log.info(userDTO.toStr());
//        User user = BeanUtil.copy(userDTO, User.class);
        User user=new User();
        user.setCode(userDTO.getCode());
        user.setPassword(userDTO.getPassword());
        user.setName(userDTO.getName());
        user.setSex(userDTO.getSex());
        user.setTel(userDTO.getTel());

        log.info("打印增加的user信息");
        log.info(user.toString());

        user.setId(idGenerator.snowflakeId());
        user.setVersion(1L);
        super.baseDataStuff4Updated(user);
        user.setPassword(Md5Utils.digestHex(user.getPassword()));

//        if (user.getPositionId().compareTo(DRIVER_ID) == 0) {
//            Driver driver = new Driver();
//            driver.setId(user.getId());
//            driver.setBirthday(user.getBirthday());
//            driver.setCode(user.getCode());
//            driver.setName(user.getName());
//            driver.setVersion(1L);
//            driver.setTel(user.getTel());
//            driver.setSex(user.getSex());
//            super.baseDataStuff4Add(driver);
//           // sendMQMessageUtil.SendMessage(ActionType.INSERT, SendMQMessageUtil.EXCHANGE_NAME, TABLE_NAME, driver);
//        }
        if (userDTO.getRoleList() == null) {
            return userMapper.insert(user) > 0;
        } else {
            userMapper.insert(user);
            UserRole userRole = new UserRole();
            List<RoleDTO> roleList = userDTO.getRoleList();
            for (RoleDTO roleDTO : roleList) {
                userRole.setId(idGenerator.snowflakeId());
                userRole.setVersion(1L);
                super.baseDataStuff4Add(userRole);
                userRole.setUserId(user.getId());
                userRole.setRoleId(roleDTO.getId());
                userRoleMapper.insert(userRole);
            }
            return true;
        }
    }

    @Override
    public Boolean remove(Long id, Long version) {
        try {
            User user = userMapper.selectByPrimaryKey(id);
            Boolean flag = false;
            if (userRoleMapper.selectByUserId(id) != null) {
                userRoleMapper.deleteAllByUserID(id);
                Example example = new Example(User.class);
                example.createCriteria().andEqualTo("id", id).andEqualTo("version", version);
                flag = userMapper.deleteByExample(example) > 0;

            }
            if (userRoleMapper.selectByUserId(id) == null) {
                Example example = new Example(User.class);
                example.createCriteria().andEqualTo("id", id).andEqualTo("version", version);
                flag = userMapper.deleteByExample(example) > 0;

            }
//            if (user.getPositionId().compareTo(DRIVER_ID) == 0) {
//                Driver driver = new Driver();
//                driver.setId(user.getId());
//                driver.setVersion(user.getVersion());
//                sendMQMessageUtil.SendMessage(ActionType.DELETE, SendMQMessageUtil.EXCHANGE_NAME, TABLE_NAME, driver);
//            }
            return flag;
        } catch (BeanException ex) {
            throw new BusinessException(BusinessErrorCode.SYSTEM_DB_CONSTRAINT_EXCEPTION, ex);
        } catch (Exception ex) {
            throw new BusinessException(UserCentreExceptionCode.BUSINESS_BASEDATA_USER_DB_EXCEPTION_CODE, ex);
        }
    }

    @Override
    public Boolean modify(UserDTO userDTO) {
        try {

            User user = BeanUtil.copy(userDTO, User.class);
            User orginUser = userMapper.selectByPrimaryKey(user.getId());
            boolean flag = false;
            if (!StringUtil.isEmpty(user.getPassword())) {
                //原密码新新密码一致不做更新
                if (user.getPassword().equals(orginUser.getPassword())) {
                    user.setPassword(null);
                } else {
                    //否则更新
                    user.setPassword(Md5Utils.digestHex(user.getPassword()));
                }
            }
            if (userDTO.getRoleList() == null) {
                flag = userMapper.updateByPrimaryKeySelective(user) > 0;
            } else {

                userMapper.updateByPrimaryKeySelective(user);
                UserRole userRole = new UserRole();
                List<RoleDTO> roleList = userDTO.getRoleList();
                if (roleList != null && !roleList.isEmpty()) {
                    userRoleMapper.deleteAllByUserID(userDTO.getId());
                    for (RoleDTO role : roleList) {
                        userRole.setId(idGenerator.snowflakeId());
                        userRole.setVersion(1L);
                        super.baseDataStuff4Add(userRole);
                        userRole.setUserId(user.getId());
                        userRole.setRoleId(role.getId());
                        userRoleMapper.insert(userRole);
                    }
                }
                flag = true;
            }
            if ((user.getPositionId() != null) && (orginUser.getPositionId().compareTo(DRIVER_ID) == 0) && (user.getPositionId().compareTo(DRIVER_ID) != 0)) {
                Driver driver = new Driver();
                driver.setId(user.getId());
                driver.setVersion(user.getVersion());
                sendMQMessageUtil.SendMessage(ActionType.DELETE, SendMQMessageUtil.EXCHANGE_NAME, TABLE_NAME, driver);
            }
            if ((user.getPositionId() != null) && (orginUser.getPositionId().compareTo(DRIVER_ID) != 0) && (user.getPositionId().compareTo(DRIVER_ID) == 0)) {
                Driver driver = new Driver();
                driver.setId(user.getId());
                driver.setBirthday(user.getBirthday());
                driver.setCode(user.getCode());
                driver.setName(user.getName());
                driver.setVersion(user.getVersion());
                driver.setTel(user.getTel());
                driver.setSex(user.getSex());
                driver.setCarrierId(1349165587770769408L);
                super.baseDataStuff4Updated(driver);
                sendMQMessageUtil.SendMessage(ActionType.INSERT, SendMQMessageUtil.EXCHANGE_NAME, TABLE_NAME, driver);
            }
            if ((user.getPositionId() != null) && (user.getPositionId().compareTo(orginUser.getPositionId()) == 0) && (orginUser.getPositionId().compareTo(DRIVER_ID) == 0)) {
                Driver driver = new Driver();
                driver.setId(user.getId());
                driver.setBirthday(user.getBirthday());
                driver.setCode(user.getCode());
                driver.setName(user.getName());
                driver.setVersion(1L);
                driver.setTel(user.getTel());
                driver.setSex(user.getSex());
                driver.setCarrierId(1349165587770769408L);
                super.baseDataStuff4Updated(driver);
                sendMQMessageUtil.SendMessage(ActionType.UPDATE, SendMQMessageUtil.EXCHANGE_NAME, TABLE_NAME, driver);
            }
            return flag;
        } catch (BeanException ex) {
            throw new BusinessException(BusinessErrorCode.SYSTEM_BEAN_COPY_EXCEPTION, ex);
        } catch (Exception ex) {
            throw new BusinessException(UserCentreExceptionCode.BUSINESS_BASEDATA_USER_DB_EXCEPTION_CODE, ex);
        }
    }

    @Override
    public Boolean modifyWithNewRole(UserDTO[] userDTOS) {
        if (userDTOS[0].getRoleList() == null) {
            return false;
        } else {
            UserRole userRole = new UserRole();
            for (UserDTO userDTO : userDTOS) {
                userRoleMapper.deleteAllByUserID(userDTO.getId());
                List<RoleDTO> roleList = userDTO.getRoleList();
                for (RoleDTO roleDTO : roleList) {
                    userRole.setId(idGenerator.snowflakeId());
                    userRole.setVersion(1L);
                    super.baseDataStuff4Updated(userRole);
                    userRole.setUserId(userDTO.getId());
                    userRole.setRoleId(roleDTO.getId());
                    userRoleMapper.insert(userRole);
                }
            }
            return true;
        }


    }

    @Override
    public List<User> commonQuery(UserQuery userQuery) {
        if (userQuery == null) {
            throw new BusinessException(BusinessErrorCode.SYSTEM_SERVICE_ARGUMENT_NOT_VALID, new Exception("commonQuery 方法错误"));
        }
        try {
            User user = new User();
            user.setName(userQuery.getName());
            user.setCode(userQuery.getCode());
            user.setTel(userQuery.getTel());
            user.setPositionId(userQuery.getPositionId());
            user.setDepartmentId(userQuery.getDepartmentId());


            if (userQuery.getRoleId() == null) {
                List<User> userList = userMapper.commonQuery(user);
                for (User currentUser : userList) {
                    currentUser.setRoleList(roleMapper.selectRoleByUserid(currentUser.getId()));
                    currentUser.setPassword(Md5Utils.digestHex(currentUser.getPassword()));
                }
                Page page = (Page) userList;
                BaseContextHolder.set("pageInfo", JSON.toJSONString(new MyPageInfo(page.getTotal(), page.getPages())));
                return userList;
            } else {
                List<User> users = userMapper.commonByQueryRoleId(user, userQuery.getRoleId());

                for (User currentUser : users) {
                    currentUser.setRoleList(roleMapper.selectRoleByUserid(currentUser.getId()));
                    currentUser.setPassword(Md5Utils.digestHex(currentUser.getPassword()));
                }
                Page page = (Page) users;
                BaseContextHolder.set("pageInfo", JSON.toJSONString(new MyPageInfo(page.getTotal(), page.getPages())));
                return users;
            }

        } catch (BeanException ex) {
            throw new BusinessException(BusinessErrorCode.SYSTEM_BEAN_COPY_EXCEPTION, ex);
        } catch (Exception ex) {
            throw new BusinessException(UserCentreExceptionCode.BUSINESS_BASEDATA_USER_DB_EXCEPTION_CODE, ex);

        }
    }

    @Override
    public User queryById(Long id) {
        User user = userMapper.selectById(id);
        user.setPassword(Md5Utils.digestHex(user.getPassword()));
        if (user == null) {
            return null;
        }
        List<Role> roles = roleMapper.selectRoleByUserid(id);
        user.setRoleList(roles);
        return user;
    }

    @Override
    public List<Role> queryAllRole() {

        return roleMapper.selectList();
    }

    @Override
    public List<Department> queryAllDepartment() {
        return departmentMapper.selectList();
    }

    @Override
    public List<Position> queryAllPosition() {
        return positionMapper.selectList();
    }

    @Override
    public Boolean batchUpdate(UserDTO[] userDTOS) {

        Assert.noNullElements(userDTOS, "更新数组不能为空");
        for (UserDTO userDTO : userDTOS) {
            User user = BeanUtil.copy(userDTO, User.class);
            int result = userMapper.updateStatus(user);
            Assert.isTrue(result > 0, "没有找到相应id更新记录");
        }
        return true;
    }

    @Override
    public Boolean batchDelete(UserDTO[] userDTOS) {
        Assert.noNullElements(userDTOS, " 批量删除数组不能为空");
        for (UserDTO userDTO : userDTOS) {
            User user = userMapper.selectByPrimaryKey(userDTO.getId());

            try {
                Boolean flag = false;
                if (userRoleMapper.selectByUserId(userDTO.getId()) != null) {
                    userRoleMapper.deleteAllByUserID(userDTO.getId());
                    Example example = new Example(User.class);
                    example.createCriteria().andEqualTo("id", userDTO.getId()).andEqualTo("version", userDTO.getVersion());
                    flag = userMapper.deleteByExample(example) > 0;


                }
                if (userRoleMapper.selectByUserId(userDTO.getId()) == null) {
                    Example example = new Example(User.class);
                    example.createCriteria().andEqualTo("id", userDTO.getId()).andEqualTo("version", userDTO.getVersion());
                    flag = userMapper.deleteByExample(example) > 0;

                }
                if (flag) {
                    if (user.getPositionId().compareTo(DRIVER_ID) == 0) {
                        Driver driver = new Driver();
                        driver.setId(userDTO.getId());
                        driver.setVersion(userDTO.getVersion());
                        sendMQMessageUtil.SendMessage(ActionType.DELETE, SendMQMessageUtil.EXCHANGE_NAME, TABLE_NAME, driver);
                    }
                }

            } catch (BeanException ex) {
                throw new BusinessException(BusinessErrorCode.SYSTEM_DB_CONSTRAINT_EXCEPTION, ex);
            } catch (Exception ex) {
                throw new BusinessException(UserCentreExceptionCode.BUSINESS_BASEDATA_USER_DB_EXCEPTION_CODE, ex);
            }

        }

        return true;
    }

    @Override
    public Boolean firstStartMd5() {
        List<User> users = userMapper.selectAll();
        Example example = new Example(User.class);
        for (User user : users) {
//            User newUser = new User();
//            newUser.setId(user.getId());
//            newUser.setPassword(Md5Utils.digestHex(user.getPassword()));
//            newUser.setStatus(null);
//            example.createCriteria().andEqualTo("id", newUser.getId());
//            userMapper.updateByExampleSelective(newUser, example);
//            example.clear();
        }
        return true;
    }

    @Transactional
    @Override
    public Boolean pcpUserRegister(List<PcpUserDTO> pcpUserDTOS) {

        try {
            pcpUserDTOS.stream().forEach(item -> {
                User user = new User();
                user.setVersion(1L);
                user.setId(item.getId());
                user.setBirthday(item.getBirthday());
                user.setCode(item.getTel());
                user.setPassword(Md5Utils.digestHex(item.getPassword()));

                user.setName(item.getName());
                user.setTenantId(1337940702788714496L);
                super.baseDataStuff4Add(user);

                Boolean flag = userMapper.insert(user) > 0;
                if (flag) {
                    UserRole userRole = new UserRole();
                    userRole.setId(idGenerator.snowflakeId());
                    userRole.setUserId(user.getId());
                    userRole.setRoleId(1337645864428109824L);
                    userRole.setStatus((byte) 0);
                    userRole.setVersion(1L);
                    super.baseDataStuff4Add(userRole);
                    userRoleMapper.insert(userRole);
                }

            });
            return true;
        } catch (Exception e) {
            throw new BusinessException("505", "用户注册失败");
        }
    }

    @Override
    public Boolean pcpUserUpdate(List<PcpUserDTO> pcpUserDTOS) {

        try {
            pcpUserDTOS.stream().forEach(item -> {
                if (item.getId() != null) {
                    User user = new User();
                    user.setId(item.getId());
                    user.setPassword(Md5Utils.digestHex(item.getPassword()));
                    user.setStatus(null);
                    Example example = new Example(User.class);
                    example.createCriteria().andEqualTo("id", user.getId());
                    userMapper.updateByExampleSelective(user, example);
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public Boolean updateUserLockStatus(List<PcpUserDTO> pcpUserDTOS) {

        Example example=new Example(User.class);

        try {
            for (PcpUserDTO pcpUserDTO : pcpUserDTOS) {
                User copy = BeanUtil.copy(pcpUserDTO, User.class);
                example.createCriteria().andEqualTo("id", copy.getId());
                copy.setVersion(null);
                copy.setUpdatedTime(Calendar.getInstance().getTime());
                userMapper.updateByExampleSelective(copy,example);
                example.clear();
            }
            return true;
        } catch (Exception e) {
            throw e;
        }
    }
}
